package com.lagou.edu.factory;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Repository;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.annotation.Transactional;
import com.lagou.edu.utils.ClassUtil;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class BeanFactory {
    // 存储对象
    //存放注解对象的容器
    private static ConcurrentHashMap<String,Object>  beans =new ConcurrentHashMap<String,Object>();;

    //包路径


    //存放beans
    private static List<Class<?>> classes;

    static {
        Properties properties = readPropertiesFile();
        final String BASE_PACKAGE = properties.getProperty("base-package");
        //扫描表 加载指定类
        classes = ClassUtil.getClasses(BASE_PACKAGE);

        if(classes.size()> 0){

            //第一步 获取 @Service  注解类  并将其实例化
            for (Class<?> clazz:classes){
                Service annotation =clazz.getDeclaredAnnotation(Service.class);
                if(annotation !=null){
                    String beanId  =annotation.value();

                    if (beanId.trim().equals("") ){
                        String className = clazz.getInterfaces()[0].getSimpleName();
                         beanId = toLowerCaseFirstOne(className);
                    }

                    Object bean = null;
                    try {
                        bean = clazz.newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    beans.put(beanId,bean);
                }
            }


            //第一步 获取 @Repository  注解类  并将其实例化
            for (Class<?> clazz:classes){
                Repository annotation =clazz.getDeclaredAnnotation(Repository.class);
                if(annotation !=null){
                    String beanId  =annotation.value();
                   if(beanId.trim().equals("")) {
                        String className = clazz.getSimpleName();
                        beanId = toLowerCaseFirstOne(className);
                    }
                    Object bean = null;
                    try {
                        bean = clazz.newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    beans.put(beanId,bean);
                }
            }



            /**
             * @Autowired
             */
            //遍历所有的注解对象
            Set<Map.Entry<String, Object>> entrySet = beans.entrySet();
            for (Map.Entry<String, Object> entry:entrySet){
                //获取注解对象，判断是否有属性的依赖注入
                Object value = entry.getValue();
                try {
                    //使用反射机制获取当前类的所有属性
                    Class<? extends Object> class1 = value.getClass();
                    Field[] fields =  class1.getDeclaredFields();
                    for (Field field:fields){
                        Autowired autowired = field.getDeclaredAnnotation(Autowired.class);
                        if(autowired !=null){
                            //获取属性名称
                            String name =autowired.value();
                            if (name.trim().equals("")){
                                String className = field.getName();
                                name = toLowerCaseFirstOne(className);
                            }
                            Object bean =getBean(name);
                            field.setAccessible(true);
                            //给属性赋值
                            field.set(value,bean);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            /**
             * @Transactional
             */
            for (Class<?> clazz:classes){
                Transactional transactional =clazz.getDeclaredAnnotation(Transactional.class);
                if(transactional !=null){
                    Service serviceAnnotation =clazz.getDeclaredAnnotation(Service.class);
                    //获取原对象
                    String beanId  =serviceAnnotation.value();
                    if (beanId.trim().equals("") ){
                        String className = clazz.getInterfaces()[0].getSimpleName();
                        beanId = toLowerCaseFirstOne(className);
                    }
                    Object oBean = beans.get(beanId);//被代理对象
                    //转为代理对象
                    ProxyFactory proxyFactory = (ProxyFactory) beans.get("proxyFactory");
                    Object proxy = proxyFactory.getJdkProxy(oBean);//代理对象
                    //代理对象替换原对象
                    beans.put(beanId,proxy);
                }

            }
        }


    }
    public static Object getBean(String beanId) {

        //从bean对象池map中获取
        Object bean = beans.get(beanId);
        return bean;
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0))){
            return s;
        }else{
            return (new StringBuffer()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }


    private static Properties readPropertiesFile() {
        Properties pros = new Properties();
        try {
            InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("application.properties");
            pros.load(new InputStreamReader(resourceAsStream, "UTF-8"));
            return pros;
        } catch (Exception e) {
            System.err.println("读取失败");
            e.printStackTrace();
        }
        return null;
    }

}
